package com.example.forum.controller;

import com.example.forum.common.AppResult;
import com.example.forum.common.ResultCode;
import com.example.forum.config.AppConfig;
import com.example.forum.model.Article;
import com.example.forum.model.ArticleReply;
import com.example.forum.model.User;
import com.example.forum.services.IArticleReplyService;
import com.example.forum.services.IArticleService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.NonNull;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;


import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.List;

@Api(tags = "帖子回复接口")
@Slf4j
@RestController
@RequestMapping("/reply")
public class ArticleReplyController {
    @Resource
    private IArticleReplyService articleReplyService;
    @Resource
    private IArticleService articleService;


    @ApiOperation("获取回复列表")
    @GetMapping("/getReplies")
    public AppResult<List<ArticleReply>> getRepliesByArticleId(@ApiParam("帖子id") @RequestParam("articleId") @NonNull Long articleId){
        //校验帖子是否存在
        Article article = articleService.selectDetailById(articleId);
        if (article == null || article.getState() == 1) {
            return AppResult.failed(ResultCode.FAILED_ARTICLE_NOT_EXISTS);
        }
        // 调用Service
        List<ArticleReply> articleReplies = articleReplyService.selectByArticleId(articleId);
        // 返回结果
        return AppResult.success(articleReplies);
    }

    @ApiOperation("创建帖子回复")
    @PostMapping("/create")
    public AppResult reply(HttpServletRequest request,
                           @ApiParam(value = "帖子id") @RequestParam(value = "articleId") @NonNull Long articleId,
                           @ApiParam(value = "帖子回复") @RequestParam(value = "content") @NonNull String content){

        //获取当前用户session
        HttpSession session = request.getSession(false);
        User user = (User) session.getAttribute(AppConfig.USER_SESSION);
        //校验用户状态
        if (user.getDeleteState() == 1) {
            return AppResult.failed(ResultCode.FAILED_USER_BANNED);
        }

        //获取帖子对象
        Article article = articleService.selectById(articleId);
        //校验帖子
        if (article == null || article.getDeleteState() == 1){
            return AppResult.failed(ResultCode.FAILED_ARTICLE_NOT_EXISTS);
        }
        // 是否封帖
        if (article.getState() == 1) {
            // 表示已封贴
            return AppResult.failed(ResultCode.FAILED_ARTICLE_BANNED);
        }
        //构造回复对象
        ArticleReply articleReply = new ArticleReply();
        articleReply.setArticleId(articleId);
        articleReply.setContent(content);
        articleReply.setPostUserId(user.getId());
        //写入回复
        articleReplyService.create(articleReply);
        //返回结果
        return AppResult.success("回复成功");
    }
}
